package com.uziot.bucket.captcha.web;

import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author shidt
 * @version V1.0
 * @className CaptchaController
 * @date 2020-12-03 21:32:04
 * @description
 */
@RestController
public class CaptchaController {

    /**
     * 验证码 redis key
     */
    public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
    /**
     * 验证码有效期（分钟）
     */
    public static final Integer CAPTCHA_EXPIRATION = 2;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Object getCode() {
        // 生成随机字串

        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String verifyCode = captcha.text();

        // 唯一标识
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String verifyKey = CAPTCHA_CODE_KEY + uuid;

        // 保存到Redis中
        //redisService.setCacheObject(verifyKey, verifyCode, CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        HashMap<String, Object> resMap = new HashMap<>(2);
        resMap.put("uuid", uuid);
        resMap.put("img", captcha.toBase64());
        return resMap;
    }
}
